import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction } from 'express';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { CommonException } from '../exception/common.exception';
@Injectable()
export class JwtMiddleware implements NestMiddleware {
  constructor(
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
  ) {}
  use(req: any, res: Response, next: NextFunction) {
    const token = req.headers?.authorization?.split(' ')[1];
    // console.log('====token==', token);
    // const decodedToken = this.jwtService.verify(token);
    if (this.noNeedCheck().includes(req.url)) {
      next();
    } else {
      try {
        const decodedToken = this.jwtService.verify(token, {
          secret: this.configService.get('jwt.secret'),
        });
        if (token) {
          req.user = {
            userId: decodedToken.userId,
            username: decodedToken.username,
            password: decodedToken.password,
          };
        }
      } catch (error) {
        throw new CommonException(500, 'token过期或token错误，请重新登录');
      }
      next();
    }
  }
  noNeedCheck() {
    return [
      '/auth/login',
      '/auth/register',
      '/auth/captchaImage',
      '/auth/logout',
    ];
  }
}
